﻿
#-*- cdg:UTF-8-*-
# -*- coding: UTF-8 -*-

import requests
import json
import time
import random
import hashlib
import re

import numpy as np
import cv2
import ddddocr
import base64

import execjs

from PIL import Image

import cBezier as Bezier

import random
import time
import numpy as np
from scipy.interpolate import interp1d


# from captcha_recognizer import Recognizer


# def slider_captcha():

#     recognizer = Recognizer()

#     # 缺口定位（返回坐标与置信度）

#     box, confidence = recognizer.identify_gap('bg.jpg')

#     print(f"缺口坐标：{box} | 置信度：{confidence:.2%}")

    # 轨迹生成（防检测关键）

# def get_track(distance):

#     # 实现缓动轨迹算法

#     return track_points


def captcha_test(tracks):

    with open('slider_captcha.js', 'r', encoding='utf-8') as fp:
        js = fp.read()
    ctx = execjs.compile(js)

    # token = ctx.call("get_token", url, originUrl)
    token = ctx.call("get_token",tracks)
    return token



def generate_track(distance):
    def __ease_out_expo(step):
        return 1 if step == 1 else 1 - pow(2, -10 * step)
 
    tracks = [[random.randint(20, 60), random.randint(10, 40), 0]]
    count = 30 + int(distance / 2)
    _x, _y = 0, 0
    for item in range(count):
        x = round(__ease_out_expo(item / count) * distance)
        t = random.randint(10, 20)
        if x == _x:
            continue
        tracks.append([x - _x, _y, t])
        _x = x
    tracks.append([0, 0, random.randint(200, 300)])
    times = sum([track[2] for track in tracks])
    return tracks, times


def generate_distance(slice_url, bg_url):
    """
    :param bg_url: 背景图地址
    :param slice_url: 滑块图地址
    :return: distance
    :rtype: Integer
    """
    slice_image = np.asarray(bytearray(requests.get(slice_url).content), dtype=np.uint8)
    slice_image = cv2.imdecode(slice_image, 1)
    slice_image = cv2.Canny(slice_image, 255, 255)
 
    bg_image = np.asarray(bytearray(requests.get(bg_url).content), dtype=np.uint8)
    bg_image = cv2.imdecode(bg_image, 1)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image, 5, 50)
    bg_image = cv2.Canny(bg_image, 255, 255)
 
    result = cv2.matchTemplate(bg_image, slice_image, cv2.TM_CCOEFF_NORMED)
 
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
 
    return max_loc[0]

def generate_distance_cv(slice_url, bg_url):
    """
    :param bg_url: 背景图地址
    :param slice_url: 滑块图地址
    :return: distance
    :rtype: Integer
    """

    with open(slice_url, 'rb') as file:
        slice_image = file.read()

    with open(bg_url, 'rb') as file:
        bg_image = file.read()

    slice_image = np.asarray(bytearray(slice_image), dtype=np.uint8)
    slice_image = cv2.imdecode(slice_image, 1)
    slice_image = cv2.Canny(slice_image, 255, 255)
 
    bg_image = np.asarray(bytearray(bg_image), dtype=np.uint8)
    bg_image = cv2.imdecode(bg_image, 1)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image, 5, 50)
    bg_image = cv2.Canny(bg_image, 255, 255)
 
    result = cv2.matchTemplate(bg_image, slice_image, cv2.TM_CCOEFF_NORMED)
 
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
 
    return max_loc[0]



def generate_distance(slice_url, bg_url):
    """
    :param bg_url: 背景图地址
    :param slice_url: 滑块图地址
    :return: distance
    :rtype: Integer
    """
    slide = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)
    slice_image = requests.get(slice_url).content
    bg_image = requests.get(bg_url).content
    result = slide.slide_match(target_bytes, bg_image, simple_target=True)
    return result['target'][0]


def generate_distance1(slice_url, bg_url):
    """
    :param bg_url: 背景图地址
    :param slice_url: 滑块图地址
    :return: distance
    :rtype: Integer
    """
    slide = ddddocr.DdddOcr(det=False, ocr=False, show_ad=False)

    with open(slice_url, 'rb') as file:
        slice_image = file.read()

    with open(bg_url, 'rb') as file:
        bg_image = file.read()

    # slice_image = requests.get(slice_url).content
    # bg_image = requests.get(bg_url).content
    
    result = slide.slide_match(slice_image, bg_image, simple_target=True)
    return result['target'][0]



# 生成滑块轨迹的方法
def get_track(x):
    # 初速度
    v = 0
    # 单位时间，统计轨迹 多时间内的位置
    t = 0.1
    # t = random.randint(2, 3) / 10
    # 轨迹列表
    tracks = []
    # 当前的位移
    current = 0
    # 到达mid值的时候减速 前4/5段加速 后1/5减速
    mid = x * 4 / 5
    while current < x:
        if current < mid:
            a = random.randint(12, 13)  # 加速
            # a = 2
        else:
            # a = -3  # 减速
            a = -random.randint(12, 13)  # 减速
        v0 = v
        v = v0 + a * t
        # 位移公式: s=V0t+(at^2)/2     # 物理公式
        s = v0 * t + 1 / 2 * a * t * t
        # 当前位置
        current += s
        # 添加到轨迹列表
        tracks.append(round(s))
    # 反着滑动大概位置
    for i in range(3):
        tracks.append(-random.randint(12, 13))
    return tracks   # 返回轨迹列表

    # 使用线性插值生成点
    curve_points = linear_interpolation(start, end, num_points)
    
    # 生成时间点
    t_values = np.linspace(0, duration, num_points)
    start_time = time.time()
    time_points = [start_time + t for t in t_values]
    
    # 生成轨迹
    trajectory = list(zip(curve_points, time_points))
    
    return trajectory

def linear_interpolation(start, end, num_points):
    """
    使用线性插值生成从起点到终点的点。
    
    :param start: 起点坐标 (x, y)
    :param end: 终点坐标 (x, y)
    :param num_points: 要生成的点数
    :return: 生成的点列表 [(x, y), ...]
    """
    points = []
    for i in range(num_points):
        t = i / (num_points - 1)
        x = start[0] + t * (end[0] - start[0])
        y = start[1] + t * (end[1] - start[1])
        points.append((round(x), round(y)))
    return points


def generate_mouse_trajectory(start, end, duration=3000.0, num_points=100):
    """
    生成鼠标运动轨迹。
    
    :param start: 起点坐标 (x, y)
    :param end: 终点坐标 (x, y)
    :param duration: 总时长（秒）
    :param num_points: 轨迹点数量
    :return: 包含 (x, y, time,mouseevent) 的轨迹列表
    """
    # 使用线性插值生成点
    curve_points = linear_interpolation(start, end, num_points)

    # 添加随机扰动使轨迹更自然
    curve_points = [
        (x + random.randint(-2, 2), y + random.randint(-2, 2))
        for x, y in curve_points
    ]
    curve_points[0]=start
    curve_points[-1]=end

    # 生成时间点
    t_values = np.linspace(0, duration, num_points)
    start_time = int(time.time()*1000)
    int_t_values = [int(t) for t in t_values]

    time_points = [start_time + t for t in int_t_values]
    
    # 生成轨迹
    #trajectory = list(zip(curve_points, time_points))
    

     # 生成轨迹 (x, y, time)
    trajectory = [(x, y, t,"mousemove") for (x, y), t in zip(curve_points, time_points)]


    # x,y,t,e=trajectory[0]
    # trajectory[0]=(x,y,t,"mousedown")

    # x,y,t,e=trajectory[-1]
    # trajectory[-1]=(x,y,t,"mouseup")


    # 将trajectory的第一个元素转换为列表，修改后转换回元组
    trajectory[0] = list(trajectory[0])
    trajectory[0][3] = "mousedown"
    trajectory[0] = tuple(trajectory[0])

    # 将trajectory的最后一个元素转换为列表，修改后转换回元组
    trajectory[-1] = list(trajectory[-1])
    trajectory[-1][3] = "mouseup"
    trajectory[-1] = tuple(trajectory[-1])    
    return trajectory









if __name__ == '__main__':
 

    s="唐伟"

    print(len(s))
    encodes_s=s.encode('utf-8')
    print(encodes_s)
    print(len(encodes_s))
    print(type(encodes_s))


    print(hex(encodes_s)) 











    